#include "FileIO.h"

FileIO::FileIO()
{

}

FileIO *FileIO::getInstance() {
    static FileIO* inst=0;
    if(!inst)inst = new FileIO();
    return inst;
}

void FileIO::saveFile(const char *fileName)
{
    if(FILE* f=fopen(fileName,"wb+"))
    {
        for(int i=0;i<WORLD_XSIZE;i++)
            for(int j=0;j<WORLD_YSIZE;j++)
                for(int k=0;k<WORLD_ZSIZE;k++)
                    if(fwrite(&(REND->getVoxel(i,j,k)),sizeof(voxel),1,f)!=1)goto die;

        fflush(f);
        fclose(f);
        return;

        die:
        fclose(f);
        printf("File Write failed");
    }
}

void FileIO::loadFile(const char *fileName)
{
    if(FILE* f=fopen(fileName,"rb"))
    {
        voxel v;
        int sz;

        fseek(f,0,SEEK_END);
        long size=ftell(f);
        if(size < FN_MAX_SIZE)goto file_len_die;
        fseek(f,0,SEEK_SET);

        for(int i=0;i<WORLD_XSIZE;i++)
            for(int j=0;j<WORLD_YSIZE;j++)
                for(int k=0;k<WORLD_ZSIZE;k++)
                {
                    if((sz=fread(&v,sizeof(voxel),1,f))!=1)goto read_die;
                    if(v.draw())REND->addVoxel(i,j,k,v);
                }
        fclose(f);
        return;

        read_die:
        fclose(f);
        printf("File Read failed %d",sz);
        return;

        file_len_die:
        fclose(f);
        printf("File length failed");
        return;

    }
}
